using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.IO;
using System.IO.Compression;
using System.Xml.Serialization;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

using Core.Mapping;
using Core.Graphics;
using SerializationUtilities;
using WorldEditor.Import.FromImage;
using WorldEditor.Tiles;
using Core.Graphics.Tiles;
using Core.Graphics.Layers;
using Core;
using WorldEditor.MapEditor;
using WorldEditor.Zones;

namespace WorldEditor
{
    public partial class Editor : Form
    {
        TileWorld _World;

        private string _WorldDirectoryPath;

        public Editor()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.Focus();
        }

        #region WorldEditing
        private void tsmNew_Click(object sender, EventArgs e)
        {
            NewWorld();
        }

        private void newToolStripButton_Click(object sender, EventArgs e)
        {
            NewWorld();
        }

        protected void NewWorld()
        {
            if (fbdNewWorld.ShowDialog() == DialogResult.OK)
            {
                //Copy selected folder path to our string
                _WorldDirectoryPath = fbdNewWorld.SelectedPath;
                _World = CreateWorld(_WorldDirectoryPath);
                //Save world
                Save();

                ConnectWorld();
            }
        }

        public TileWorld CreateWorld(string WorldPath)
        {
            return TileWorld.NewWorld(WorldPath);
        }

        private void ConnectWorld()
        {
            //create Map editor and world zones forms
            MapEditorChildForm mecf = new MapEditorChildForm();
            WorldZonesChildForm wzcf = new WorldZonesChildForm();

            mecf.MdiParent = this;
            wzcf.MdiParent = this;

            //load textures
            TileSetLoaderHelper.LoadTileSets(TileWorld.CurrentWorld.diTextures.FullName, TileSetTypes.Terrain, mecf.Graphics);
            
            //show windows and maximize
            mecf.Show();
            wzcf.Show();

            mecf.WindowState = FormWindowState.Maximized;
            wzcf.WindowState = FormWindowState.Maximized;


        }

        private void setToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //string coord = txtGoTo.Text;
            ////Remove any spaces
            //coord = coord.Replace(" ", "");

            ////Check Regular Expression on text
            ////Should match ######x#######
            //Regex rx = new Regex("[0-9]+x[0-9]+");
            //if (rx.IsMatch(coord))
            //{
            //    //Calculate x,y value pair for the upper left corner of the world.
            //    int x = Convert.ToInt32(coord.Substring(0, coord.IndexOf("x")));
            //    int y = Convert.ToInt32(coord.Substring(coord.IndexOf("x") + 1));
            //    //Prepare a rectangle and set it's values
            //    Rectangle drawarea = mapEditor1.DrawArea;
            //    drawarea.X = x;
            //    drawarea.Y = y;
            //    //Set the new draw area
            //    mapEditor1.DrawArea = drawarea;
            //}
            //else
            //{
            //    //if the text was no good, ie didn't pass the regex then kill it
            //    txtGoTo.Text = tsWorldCoordinates.Text;
            //}
        }

        private void mapGridToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //mapEditor1.DrawGrid = !mapEditor1.DrawGrid;

            //mapGridToolStripMenuItem.Checked = mapEditor1.DrawGrid;
        }

        #endregion

        #region FileActions
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenWorld();
        }

        private void openToolStripButton_Click(object sender, EventArgs e)
        {
            OpenWorld();
        }

        protected void OpenWorld()
        {
            if (fbdOpenWorld.ShowDialog() == DialogResult.OK)
            {
                _WorldDirectoryPath = fbdOpenWorld.SelectedPath;
                _World = TileWorld.LoadWorld(_WorldDirectoryPath);
                //Connect World to GUI
                ConnectWorld();
            }
        }

        private void saveToolStripButton_Click(object sender, EventArgs e)
        {
            Save();
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Save();
        }

        private void Save()
        {
            _World.SaveWorld();
        }
        /// <summary>
        /// Saves World file and zone information
        /// </summary>

        #endregion

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Bring up some sort of box asking if they want to save changes, or w/e
            this.Save();
            //Then Exit
            this.Close();
        }

        private void toolStripMenuItem15_Click(object sender, EventArgs e)
        {
            SystemManager.SystemManager sys = new SystemManager.SystemManager();

            sys.Show(this);
        }

        private void mapFromImageToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MapFromImage mff = new MapFromImage(_World);

            mff.Show();
        }

        private void tsbResources_Click(object sender, EventArgs e)
        {
            //ResourceManager.ResourceManager rm = new WorldEditor.ResourceManager.ResourceManager(mapEditor1.GraphicsDevice);

            //rm.ShowDialog(this);
        }

        private void toolStripMenuItem18_Click(object sender, EventArgs e)
        {
            //get map editor form
            foreach (Form f in this.MdiChildren)
            {
                if (f is MapEditorChildForm)
                {
                    MapEditorChildForm mecf = (MapEditorChildForm)f;

                    ResourceManager.ResourceManager rm = new WorldEditor.ResourceManager.ResourceManager(mecf.Graphics);

                    rm.Show();

                    return;
                }
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            TileGroupingManage tg = new TileGroupingManage();

            tg.Show();

            tg.FormClosed += new FormClosedEventHandler(tg_FormClosed);
        }

        void tg_FormClosed(object sender, FormClosedEventArgs e)
        {

            AutoTileInfo ati = AutoTileInfoCollection.GlobalAutoTileSets[0];

            AutoTileLayer atl = new AutoTileLayer(ati);
            atl.Height = 128;
            atl.Width = 128;

            atl.Tiles = TileCollection.GetTilesForEmptyTileLayer(128, 128);
            atl.BaseAutoLayer.Tiles = TileCollection.GetTilesForEmptyTileLayer(128, 128);

            //Single Tile
            atl.BaseAutoLayer.SetTileAtLocation(ati.Plain, 12, 12);

            //Cross formation
            atl.BaseAutoLayer.SetTileAtLocation(ati.Plain, 5, 4);
            atl.BaseAutoLayer.SetTileAtLocation(ati.Plain, 5, 6); 
            atl.BaseAutoLayer.SetTileAtLocation(ati.Plain, 5, 5);
            atl.BaseAutoLayer.SetTileAtLocation(ati.Plain, 6, 5);
            atl.BaseAutoLayer.SetTileAtLocation(ati.Plain, 4, 5);

            atl.UpdateDrawingLayer();

            //Map tm = mapEditor1.World.Zones[0].Maps[0];

            //tm.Layers.Add(atl);

            //LayerCollection tlc = new LayerCollection();
            //tlc.Add(atl);

            //Removed Auto Tile Layer picker from screen.  Should integrate this feature with standard tile usage instead
            //tileLayerManager1.LoadLayers(tlc);
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            ////Test load in an animated tile, make it work on screen, then worry about editor/manager
            //AnimatedTile at = new AnimatedTile(0, 0, 500, Core.Graphics.Animations.AnimationTypes.Loop);

            ////Create 5 frames and add them in
            //at.TileAnimation.Frames.Add(new Core.Graphics.Animations.AnimationFrame(TileSetCollection.GlobalTerrainTileSets[0].Tiles[0].Tile));
            //at.TileAnimation.Frames.Add(new Core.Graphics.Animations.AnimationFrame(TileSetCollection.GlobalTerrainTileSets[0].Tiles[1].Tile));
            //at.TileAnimation.Frames.Add(new Core.Graphics.Animations.AnimationFrame(TileSetCollection.GlobalTerrainTileSets[0].Tiles[2].Tile));
            //at.TileAnimation.Frames.Add(new Core.Graphics.Animations.AnimationFrame(TileSetCollection.GlobalTerrainTileSets[0].Tiles[3].Tile));
            //at.TileAnimation.Frames.Add(new Core.Graphics.Animations.AnimationFrame(TileSetCollection.GlobalTerrainTileSets[0].Tiles[4].Tile));

            ////add it to the first tile set
            //TileSetCollection.GlobalTerrainTileSets[0].AnimatedTiles.Add(at);

            ////Set it as the current drawing tile
            //mapEditor1.PrimaryTile = at;
        }

        private void aboutToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            //on about click, show about form
            AboutWorldEditor awe = new AboutWorldEditor();

            awe.ShowDialog();
        }
    }
}